<template>
  <div>
    <div ref="canvasContainer" class="scene-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const canvasContainer = ref(null);
onMounted(() => {
  canvasContainer.value.appendChild(renderer.domElement);
});

// 场景初始化
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
const renderer = new THREE.WebGLRenderer({
  antialias: true, // 抗锯齿
});
renderer.setSize(window.innerWidth, window.innerHeight);
// document.body.appendChild(renderer.domElement);

// 控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // 阻尼惯性

// camera.position.z = 5;

// 光源
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 5, 5);
scene.add(directionalLight);

// 模型加载
const loader = new GLTFLoader();
let model, upperBodyBones;
const ROTATION_LIMIT = { x: Math.PI / 6, y: Math.PI / 4 };
let currentRotation = { x: 0, y: 0 };
let isRotating = false;

loader.load(
  "https://threejs.org/examples/models/gltf/LeePerrySmith/LeePerrySmith.glb",
  (gltf) => {
    model = gltf.scene;
    model.scale.set(1.5, 1.5, 1.5); // 调整模型大小
    scene.add(model);

    // 提取上半身骨骼
    upperBodyBones = {
      spine: model.getObjectByName("Spine"),
      chest: model.getObjectByName("Chest"),
      leftShoulder: model.getObjectByName("LeftShoulder"),
      rightShoulder: model.getObjectByName("RightShoulder"),
    };

    console.log("模型加载完成");
  }
);

const size = 20; // 网格大小
const divisions = 20; // 网格分割数
const gridHelper = new THREE.GridHelper(size, divisions, 0xffffff);
// scene.add(gridHelper);

camera.position.set(0, 2, 15); // 设置相机位置

// 鼠标控制
document.addEventListener("mousemove", (event) => {
  if (!upperBodyBones || !isRotating) return;

  const deltaX = event.movementX / window.innerWidth;
  const deltaY = event.movementY / window.innerHeight;

  currentRotation.y = Math.max(
    -ROTATION_LIMIT.y,
    Math.min(ROTATION_LIMIT.y, currentRotation.y + deltaX * 2)
  );
  currentRotation.x = Math.max(
    -ROTATION_LIMIT.x,
    Math.min(ROTATION_LIMIT.x, currentRotation.x - deltaY * 2)
  );

  if (upperBodyBones.spine && upperBodyBones.chest) {
    upperBodyBones.spine.rotation.y = currentRotation.y * 0.5;
    upperBodyBones.chest.rotation.y = currentRotation.y;
    upperBodyBones.spine.rotation.x = currentRotation.x * 0.3;
    upperBodyBones.chest.rotation.x = currentRotation.x * 0.7;
  }
});

document.addEventListener("mousedown", () => (isRotating = true));
document.addEventListener("mouseup", () => (isRotating = false));

// 动画循环
function animate() {
  requestAnimationFrame(animate);
  controls.update();

  // 添加绕X轴旋转（每秒60帧时约0.6弧度/秒）
  if (model) {
    model.rotation.y += 0.01;
  }

  renderer.render(scene, camera);
}

animate();

// 窗口大小调整
const resizeObserver = new ResizeObserver(() => {
  const container = canvasContainer.value;
  const width = container.clientWidth;
  const height = container.clientHeight;

  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  renderer.setSize(width, height);
});

onMounted(() => {
  resizeObserver.observe(canvasContainer.value);
  // 初始设置尺寸
  const { clientWidth, clientHeight } = canvasContainer.value;
  renderer.setSize(clientWidth, clientHeight);
});

onBeforeUnmount(() => {
  resizeObserver.disconnect();
});
</script>

<style scoped lang="scss">
.scene-container {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
</style>